package com.qf.dao;

import com.qf.pojo.Cart;
import com.qf.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {

    //创建dbUtils工具
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDateSource());

    @Override
    public Cart findCartByUidAndPid(Integer uid, Integer pid) {
        String sql = "select * from tb_cart where uid=? and pid=?";
        try {
            Cart cart = queryRunner.query(sql, new BeanHandler<Cart>(Cart.class), uid, pid);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateCart(Cart cart) {
        String sql = "update tb_cart set num=?, money=? where cid=?";
        try {
            queryRunner.update(sql, cart.getNum(), cart.getMoney(), cart.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertCart(Cart cart) {
        String sql = "insert into tb_cart (uid, pid, num, money) value(?, ?, ?, ?)";
        try {
            queryRunner.update(sql, cart.getUid(), cart.getPid(), cart.getNum(), cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Cart> findCartListByUid(Integer id) {
        String sql = "select * from tb_cart where uid=?";
        try {
            List<Cart> list = queryRunner.query(sql, new BeanListHandler<Cart>(Cart.class), id);
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Cart findById(Integer id) {
        String sql = "select * from tb_cart where cid=?";
        try {
            Cart cart = queryRunner.query(sql, new BeanHandler<Cart>(Cart.class), id);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteById(Integer id) {
        String sql = "delete from tb_cart where cid=?";
        try {
            queryRunner.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}